package com.w.wx.controller.WebSocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.w.wx.domain.ChatMessage;
import com.w.wx.service.ChatService;
import com.w.wx.utils.ALToHMUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@ServerEndpoint("/wx/{fromOpenid}/{toOpenid}")
@Component
public class WebSocketServer {

    public static WebSocketServer webSocketServer;
    @Autowired
    private ChatService chatService;

    @PostConstruct        //此注解的方法在bean加载前执行
    private void init() {
        webSocketServer = this;
        //初始化时将静态化的interFaceInfoMapper进行了实例化
        webSocketServer.chatService = this.chatService;
    }


	 //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全HashMap，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public void sendMessage(Session session, ChatMessage message) throws IOException {
        if(session != null){
            synchronized (session) {

                String s = JSONObject.toJSONString(message);
                System.out.println("52 发送数据：" + s);
                session.getBasicRemote().sendText(s);
            }
        }
    }
    //给指定用户发送信息
    public void sendInfo(String to_openid, ChatMessage message){
        Session session = sessionPools.get(to_openid);

        if(session == null){
            webSocketServer.chatService.addDeInfo(message);
        }else{
            try {
                sendMessage(session, message);
            }catch (Exception e){
                e.printStackTrace();
            }
        }


    }
    // 群发消息
    public void broadcast(ChatMessage message){
    	for (Session session: sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch(Exception e){
                e.printStackTrace();
                continue;
            }
        }
    }



    //收到客户端信息后，根据接收人的username把消息推下去或者群发
    // to=-1群发消息
    @OnMessage
    public void onMessage(String message) throws IOException{
        ChatMessage msg=JSON.parseObject(message, ChatMessage.class);
        sessionPools.get(msg.getToOpenid());

        webSocketServer.chatService.addInfo(message);


        if (msg.getToOpenid().equals("-1")) {
            broadcast(msg);
        } else {
            sendInfo(msg.getToOpenid(),msg);
        }

    }



    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "fromOpenid") String fromOpenid,@PathParam(value = "toOpenid") String toOpenid) throws IOException {

        ArrayList<ChatMessage> list = webSocketServer.chatService.getAllNotRead(fromOpenid,toOpenid);
        if (!list.isEmpty()) {
            Iterator<ChatMessage> it = list.iterator();
            while (it.hasNext()) {
                ChatMessage chatMessage = it.next();
                chatMessage.setContent(ALToHMUtil.toUnicode(chatMessage.getContent()));
                sendMessage(session, chatMessage);
                log.info("115 当前用户接收离线消息" + chatMessage.toString());
            }
        }

        sessionPools.put(fromOpenid, session);

        addOnlineCount();
        System.out.println("125 "+fromOpenid + "加入webSocket！当前人数为" + onlineNum);


    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "fromOpenid") String fromOpenid) throws IOException {

        Session session = sessionPools.get(fromOpenid);

        session.close();
        sessionPools.remove(fromOpenid);

        subOnlineCount();
        System.out.println(fromOpenid + "断开webSocket连接！当前人数为" + onlineNum);

    }
    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
       // System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
    
    public static AtomicInteger getOnlineNumber() {
        return onlineNum;
    }
    
    public static ConcurrentHashMap<String, Session> getSessionPools() {
        return sessionPools;
    }
}
